from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
# from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.
from django.views import View

from apps.operation.models import UserFavorite
from apps.organization.forms import AddAskForm
from apps.organization.models import CourseOrg, City, Teacher
from django.core.paginator import Paginator  # 这个是处理分页的

from djangoProject.settings import PAGINATION_SETTINGS

'''教师详情页'''


class TeacherDetailView(View):
    def get(self, request, teacher_id, *args, **kwargs):
        teacher = Teacher.objects.get(id=int(teacher_id))
        print(teacher.teacher_course())

        teacher_fav = False
        org_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):
                teacher_fav = True
            if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):
                org_fav = True

        hot_teachers = Teacher.objects.all().order_by("-click_nums")[:3]
        return render(request, "teacher-detail.html", {
            "teacher": teacher,
            "teacher_fav": teacher_fav,
            "org_fav": org_fav,
            "hot_teachers": hot_teachers
        })


'''教师列表'''


class TeacherListView(View):
    def get(self, request, *args, **kwargs):
        all_teachers = Teacher.objects.all().order_by('id')
        hot_teachers = all_teachers.order_by("-click_nums")[:3]
        teacher_nums = all_teachers.count()


        keywords = request.GET.get("keywords", "")
        s_type = "teacher"
        if keywords:
            all_teachers = all_teachers.filter(Q(name__icontains=keywords))

        print(request.GET.get('page', 1))
        # 对教师进行排序
        sort = request.GET.get("sort", "")
        if sort == "hot":
            all_teachers = all_teachers.order_by("-click_nums")

        paginator = Paginator(all_teachers, 3)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        all_teachers = paginator.get_page(page)
        return render(request, 'teachers-list.html',
                      {"all_tachers": all_teachers, 'hot_teachers': hot_teachers, 'teacher_nums': teacher_nums,
                       "sort": sort,"keywords":keywords,"s_type":s_type})


'''机构介绍'''


class OrgDescView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "desc"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        return render(request, "org-detail-desc.html",
                      {"course_org": course_org,
                       "current_page": current_page, "has_fav": has_fav})


'''机构课程'''


class OrgCourseView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "course"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        all_courses = course_org.courses_set.order_by('-students')
        paginator = Paginator(all_courses, 4)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        all_courses = paginator.get_page(page)

        return render(request, "org-detail-course.html",
                      {"all_courses": all_courses,
                       "course_org": course_org,
                       "current_page": current_page,
                       "has_fav": has_fav
                       })


'''机构讲师'''


class OrgTeacherView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "teacher"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        all_teacher = course_org.teacher_set.all().order_by('id')
        paginator = Paginator(all_teacher, 3)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        all_teacher = paginator.get_page(page)

        return render(request, "org-detail-teachers.html",
                      {"all_teacher": all_teacher,
                       "course_org": course_org,
                       "current_page": current_page,
                       "has_fav": has_fav
                       })


'''
机构详情
'''


class OrgHomeView(View):
    def get(self, request, org_id, *args, **kwargs):
        print(org_id)
        current_page = "home"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        all_teacher = course_org.teacher_set.all()[:2]
        all_course = course_org.courses_set.all().order_by("-students")[:4]
        return render(request, "org-detail-homepage.html",
                      {"course_org": course_org, "all_teacher": all_teacher, "all_course": all_course,
                       "current_page": current_page, "has_fav": has_fav})


'''
用户咨询
'''


class AddAskView(View):
    def post(self, request, *args, **kwargs):
        userAskForm = AddAskForm(request.POST)
        if userAskForm.is_valid():
            userAskForm.save(commit=True)
            return JsonResponse({"status": "success"})
        else:
            print(userAskForm.errors)
            return JsonResponse({"status": "fail", "msg": userAskForm.errors})


'''
机构列表
'''


class OrgView(View):
    def get(self, request, *args, **kwargs):
        all_orgs = CourseOrg.objects.all().order_by('id')
        hot_orgs = all_orgs.order_by("-click_nums")[:3]
        city_list = City.objects.all()
        print(request.GET.get('page', 1))
        keywords = request.GET.get("keywords", "")
        s_type = "org"
        if keywords:
            all_orgs = all_orgs.filter(Q(name__icontains=keywords) | Q(desc__icontains=keywords))


        # 通过机构类别对课程机构进行筛选
        category = request.GET.get("ct", "")
        if category:
            all_orgs = all_orgs.filter(category=category)

            # 通过所在城市对课程机构进行筛选
        city_id = request.GET.get("city", "")
        if city_id:
            if city_id.isdigit():
                all_orgs = all_orgs.filter(city_id=int(city_id))
        org_nums = all_orgs.count()

        # 对机构进行排序
        sort = request.GET.get("sort", "")
        if sort == "students":
            all_orgs = all_orgs.order_by("-students")
        elif sort == "courses":
            all_orgs = all_orgs.order_by("-courses_num")

        paginator = Paginator(all_orgs, PAGINATION_SETTINGS.get("PAGE_RANGE_DISPLAYED"))
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        all_orgs = paginator.get_page(page)
        # print(org_all.c)
        page_number = [i for i in range(1, paginator.count)]

        return render(request, "org-list.html",
                      {"org_all": all_orgs,
                       "page_number": page_number,
                       "city_list": city_list,
                       "org_nums": org_nums,
                       "category": category,
                       "city_id": city_id,
                       "sort": sort,
                       "hot_orgs": hot_orgs,
                       "keywords": keywords,
                       "s_type": s_type
                       })
